import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/erp_odd_numbers_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_details_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/pages/common/LoadBuilder.dart';
import 'package:xiongan_app_yy/provider/erp_info.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/dropdown_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/input_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/input_card_widget_new.dart';
import 'package:xiongan_app_yy/widgets/comm/scan_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_card_widget_new.dart';
import 'package:xiongan_app_yy/widgets/comm/text_exhibition_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/time_card_widget.dart';
import 'package:xiongan_app_yy/widgets/inv_list_page_new_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/notification/erp_notification.dart';
import 'package:xiongan_app_yy/widgets/notification/image_notification.dart';
import 'package:xiongan_app_yy/widgets/notification/time_notification.dart';

import '../../native_plugin.dart';

//配送预约-新建
class DeliveryListPageNew extends StatefulWidget {
  final Map<String, dynamic> args;
  final String cc = "";

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return DeliveryListPageNewState();
  }

  DeliveryListPageNew(this.args);
}

class DeliveryListPageNewState extends State<DeliveryListPageNew> {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  //获取到插件与原生的交互通道
  static const counterPlugin =
      const EventChannel('com.example.xiongan_app_yy/native');
  StreamSubscription _counterSub;
  bool visibility = true; //false不隐藏，true隐藏
  var _futureBuilderFuture;
  String time;
  List<String> imageList;
  List<File> imageFileList;
  int index;
  String data;
  String projectName = "";
  String address = "请输入地址";
  Color addressTextColor;
  bool mapOpen = false;
  String elongitude;
  String elatitude;
  bool load = false;
  String selectValue;
  String orgId;
  int textNum = 0;
  ErpOddNumbersEntity bean;
  ErpOddNumbersEntity beanNew;
  ErpOddNumbersData detailsBean;
  List<String> numberList = new List();
  TextEditingController controller = TextEditingController();
  TextEditingController controller0 = TextEditingController();
  TextEditingController controller1 = TextEditingController();
  TextEditingController controller2 = TextEditingController();
  TextEditingController controller3 = TextEditingController();
  Map<String, String> baiMap = Map();
  String projectname;
  String projectno;
  String suppliername;

  Future _gerData() async {
    var response = InternetAPI.getInstance()
        .dio
        .get("OMS/MiErpWarehouseOutOrder/GetAllErpOrder", queryParameters: {
      'operaterUserId': DataSingleton().Data.id,
      'pageNo': -1
    });
    return response;
  }

  @override
  void initState() {
    super.initState();
    if (widget.args != null) {
      InvListDetailsEntity bean = widget.args["bean"];
      selectValue = bean.datas.erpno;
      projectName = bean.datas.projectname;
      controller2.text = bean.datas.projectno;
      controller.text = bean.datas.erpno;
      address = bean.datas.destination;
      orgId = bean.datas.id;
      projectname = bean.datas.projectname;
      projectno = bean.datas.projectno;
      suppliername = bean.datas.supplyname;
    }
    _futureBuilderFuture = _gerData();
    if (_counterSub == null) {
      _counterSub = counterPlugin
          .receiveBroadcastStream()
          .listen(_onCounterEvent, onError: _onCounterError);
    }
  }

  void _onCounterError(Object error) {}

  void _onCounterEvent(Object event) {
    print(event.toString());

    if (event.toString() == "back") {
      setState(() {
        mapOpen = false;
      });
    } else if (event.toString() == "ok") {
      baiMap.clear();
    } else {
      List<String> s = event.toString().split(",");
      baiMap.putIfAbsent(s[0], () {
        return s[1].toString();
      });
      if (baiMap.length == 5) {
        setState(() {
          address = baiMap["city"].toString() +
              baiMap["district"].toString() +
              baiMap["key"].toString();
          elongitude = baiMap["longitude"];
          elatitude = baiMap["latitude"];
          mapOpen = false;
        });
      } else {
        print("呵呵");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    print("刷新");
    if ("请输入地址" == address) {
      addressTextColor = Color(0xFF999999);
    } else {
      addressTextColor = Color(0xFF323232);
    }
    return NotificationListener(
        onNotification: (notification) {
          print(notification.runtimeType);
          switch (notification.runtimeType) {
            case ErpNotification:
              index = notification.index;
              detailsBean = beanNew.datas.elementAt(index);
              setState(() {
                visibility = false;
                selectValue = notification.msg;
                projectName = detailsBean.details.elementAt(0).projectname;
                controller2.text = detailsBean.details.elementAt(0).projectno;
              });
              Provider.of<ErpInfo>(context)
                  .setMode(bean.datas.elementAt(index));
              break;
            case TimeNotification:
              time = notification.msg;
              print("测试$time");
              break;
            case ImageNotification:
              if (notification.msg == "String") {
                imageList = notification.list;
                print("图片list$imageList");
              } else {
                imageFileList = notification.fileList;
                print("图片file$imageFileList");
              }

              break;
          }
          return false;
        },
        child: Scaffold(
            key: scaffoldKey,
            appBar: AppBar(
              leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
              title: Text(
                "新建配送预约",
                style: TextStyle(fontSize: 18),
              ),
              elevation: 0,
              centerTitle: true,
              backgroundColor: Color(0xFF00A5F1),
            ),
            body: FutureBuilder(
              builder: _buildFuture,
              future: _futureBuilderFuture,
            )));
  }

  ///snapshot就是_calculation在时间轴上执行过程的状态快照
  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return _createListView(context, snapshot);
      default:
        return null;
    }
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    data = snapshot.data.toString();
    Map<String, dynamic> dataMap = jsonDecode(data);
    bean = new ErpOddNumbersEntity.fromJson(dataMap);
    beanNew = new ErpOddNumbersEntity.fromJson(dataMap);
    if (numberList.length == 0) {
      //这个判断是因为FutureBuilder在改变时会反复刷新执行builder（可能是键盘弹起造成的），会造成数据添加错乱。数据只添加一次
      bean.datas.forEach((erpOddNumbersData) {
        numberList.add(erpOddNumbersData.erpno);
      });
    }
    if (widget.args != null) {
      for (int i = 0; i < numberList.length; i++) {
        if (selectValue == numberList.elementAt(i).toString()) {
          detailsBean = bean.datas.elementAt(i);
          Provider.of<ErpInfo>(context).setMode(detailsBean);
          visibility = false;
        }
      }
    }
    textNum = 0;
    if (Provider.of<ErpInfo>(context).mode != null) {
      for (int i1 = 0;
          i1 < Provider.of<ErpInfo>(context).mode.details.length;
          i1++) {
        textNum = Provider.of<ErpInfo>(context).mode.details[i1].qty + textNum;
      }
    }
    return LoadBuilder(
        bgColor: Colors.black26,
        visibility: load,
        builder: Column(
          children: <Widget>[
            Expanded(
                child: ListView(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    InputCardWidgetNew(
                      suffixIcon: ScanWidget(
                        clickCallback: (value) {
                          controller.text = value.trim();
                          matchErpInfo(value.trim());
                        },
                      ),
                      enabled: true,
                      hintText: "请选择要配送的领料单号",
                      title: "领料单号:",
                      contro: controller,
                      onChange: () {
                        if (controller.text.length == 10) {
                          matchErpInfo(controller.text);
                        }
                      },
                      enterListen: (value) {
                        if (value.length > 0) {
                          setState(() {
                            matchErpInfo(controller.text);
                          });
                        }
                      },
                      textAction: TextInputAction.done,
                    ),
                    TextExhibitionCardWidget(
                        position: CrossAxisAlignment.start,
                        exhibitionTextColor: Color(0xFF323232),
                        title: "项目名称:",
                        exhibitionText: projectName,
                        distance: EdgeInsets.only(
                            left: 16, right: 16, bottom: 15, top: 15),
                        border: Border(
                            bottom: BorderSide(
                                width: 1, color: Color(0xffefefef)))),
                    InputCardWidget(
                      title: "编号:",
                      enabled: false,
                      contro: controller2,
                    ),
                    GestureDetector(
                        child: TextExhibitionCardWidget(
                          exhibitionTextColor: addressTextColor,
                          position: CrossAxisAlignment.start,
                          distance: EdgeInsets.only(
                              right: 15, left: 15, bottom: 16, top: 16),
                          title: "目的地:",
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffefefef))),
                          exhibitionText: address,
                        ),
                        onTap: () {
                          if (mapOpen == false) {
                            NativePlugin.openMap.then((a) {
                              if (a == "ok") {
                                setState(() {
                                  mapOpen = true;
                                });
                              }
                            });
                          }
                        }),
                    Offstage(
                        offstage: visibility,
                        child: TextCardWidgetNew(
                            onPressed: () {
                              //Navigator.pushNamed(context, "/storageDetails",arguments: detailsBean);
                              Navigator.pushNamed(context, "/storageDetails",
                                  arguments: {
                                    "type": "push",
                                    "title": "配送物资明细",
                                    "data": detailsBean,
                                    "show": true,
                                  });
                            },
                            title: "物资明细:",
                            textNum: false,
                            num: textNum.toString(),
                            border: Border.fromBorderSide(BorderSide.none))),
                    TimeCardWidget(
                        scaffoldKey: scaffoldKey,
                        custom: true,
                        hintText: "请选择预计送达时间",
                        title: "预计送达时间:",
                        margin: EdgeInsets.only(top: 20),
                        border: Border.fromBorderSide(BorderSide.none)),
                  ],
                ),
                UploadImgWidget(),
              ],
            )),
            Container(
              width: double.infinity,
              height: 48,
              child: FlatButton(
                color: Color(0XFF00A5F1),
                child: Text(
                  "提交",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: _upData,
              ),
            )
          ],
        ));
  }

  void _upData() {
    if (selectValue != null && selectValue.length > 0) {
      if (address != "请输入地址" && address.length > 0) {
        if (textNum != 0) {
          if (time != null) {
            setState(() {
              load = true;
            });
            if (imageList == null && imageFileList == null) {
              //没有图
              List<ErpOddNumbersDatasDetail> data = [];
              for (int i = 0;
                  i < Provider.of<ErpInfo>(context).mode.details.length;
                  i++) {
                if (Provider.of<ErpInfo>(context)
                        .mode
                        .details
                        .elementAt(i)
                        .qty !=
                    0) {
                  data.add(
                      Provider.of<ErpInfo>(context).mode.details.elementAt(i));
                }
              }
              InternetAPI.getInstance().post(
                "OMS/MiWarehouseOutTask/AddMiWarehouseOutTask",
                (data) {
                  if (data == true) {
                    Navigator.pop(context, "ok");
                    TostUtil.showToast("提交成功");
                  }
                },
                errorCallBack: (err) {
                  setState(() {
                    load = false;
                  });
                },
                params: {
                  "elongitude": elongitude,
                  "elatitude": elatitude,
                  "operaterUserName": DataSingleton().Data.username,
                  "operaterUserId": DataSingleton().Data.id,
                  "tenantId": DataSingleton().Data.tenantId,
                  "creationTime": DateTime.now().toString().substring(0, 19),
                  "applytime": time.substring(0, 19),
                  "erpno": selectValue,
                  "orgId": orgId,
                  "detailList": data,
                  "projectname": projectname != null
                      ? projectname
                      : detailsBean.details.elementAt(0).projectname,
                  "projectno": projectno != null
                      ? projectno
                      : detailsBean.details.elementAt(0).projectno,
                  "supplyname": suppliername != null
                      ? suppliername
                      : detailsBean.details.elementAt(0).suppliername,
                  "warehouseid": DataSingleton().warehouseChoice.id,
                  "department": data[0].department,
                  //"department": "雄安供电公司",
                  "Warehouseouttype": "20",
                  "destination": address,
                  "appointmentmode": "20"
                },
              );
            } else {
              //有图
              if (imageList.length == imageFileList.length) {
                //图上传完成
                List<ErpOddNumbersDatasDetail> data = [];
                for (int i = 0;
                    i < Provider.of<ErpInfo>(context).mode.details.length;
                    i++) {
                  if (Provider.of<ErpInfo>(context)
                          .mode
                          .details
                          .elementAt(i)
                          .qty !=
                      0) {
                    data.add(Provider.of<ErpInfo>(context)
                        .mode
                        .details
                        .elementAt(i));
                  }
                }
                List<InvListDatasImglist> img = new List();
                for (int i = 0; i < imageList.length; i++) {
                  img.add(InvListDatasImglist(imgstr: imageList.elementAt(i)));
                }
                InternetAPI.getInstance().post(
                  "OMS/MiWarehouseOutTask/AddMiWarehouseOutTask",
                  (data) {
                    if (data == true) {
                      Navigator.pop(context, "ok");
                      TostUtil.showToast("提交成功");
                    }
                  },
                  errorCallBack: (err) {
                    setState(() {
                      load = false;
                    });
                  },
                  params: {
                    "operaterUserName": DataSingleton().Data.username,
                    "operaterUserId": DataSingleton().Data.id,
                    "tenantId": DataSingleton().Data.tenantId,
                    "creationTime": DateTime.now().toString().substring(0, 19),
                    "applytime": time.substring(0, 19),
                    "erpno": selectValue,
                    "orgId": orgId,
                    "detailList": data,
                    "projectname": projectname != null
                        ? projectname
                        : detailsBean.details.elementAt(0).projectname,
                    "projectno": projectno != null
                        ? projectno
                        : detailsBean.details.elementAt(0).projectno,
                    "supplyname": suppliername != null
                        ? suppliername
                        : detailsBean.details.elementAt(0).suppliername,
                    "imgList": img,
                    "warehouseid": DataSingleton().warehouseChoice.id,
                    "department": data[0].department,
                    "Warehouseouttype": "20",
                    "destination": address,
                    "appointmentmode": "20",
                    "elongitude": elongitude,
                    "elatitude": elatitude
                  },
                );
              } else {
                TostUtil.showToast("大图上传中，请稍后");
              }
            }
          } else {
            TostUtil.showToast("请选择预约时间");
          }
        } else {
          TostUtil.showToast("物资明细不能为0");
        }
      } else {
        TostUtil.showToast("请填写地址");
      }
    } else {
      TostUtil.showToast("请输入正确的单号");
    }
  }

  void matchErpInfo(String value) {
    for (int i = 0; i < beanNew.datas.length; i++) {
      if (value == bean.datas.elementAt(i).erpno) {
        detailsBean = beanNew.datas.elementAt(i);
        projectName = detailsBean.details.elementAt(0).projectname;
        controller2.text = detailsBean.details.elementAt(0).projectno;
        Provider.of<ErpInfo>(context).setMode(bean.datas.elementAt(i));
        setState(() {
          index = i;
          visibility = false;
          selectValue = value;
        });
        return;
      }
    }
    setState(() {
      visibility = true;
      selectValue = null;
    });
    TostUtil.showToast("请输入正确的单号");
  }
}
